package cn.wsalix.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.anlaser.admin.BaseUser;
import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.shiro.token.CaptchaToken;
import cn.wsalix.shiro.token.QQToken;
import cn.wsalix.shiro.token.WxAppToken;
import cn.wsalix.vo.CommonVO;

import com.google.gson.Gson;

public class ApiAuthenticationFilter extends FormAuthenticationFilter {
	private static final Logger logger = LoggerFactory
			.getLogger(ApiAuthenticationFilter.class);
	Gson gson = new Gson();

	/*
	 * 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		Subject currentUser = SecurityUtils.getSubject();
		BaseUser user = (BaseUser) currentUser.getPrincipal();
		Session session = currentUser.getSession();
		
		return true;
		/*
		 * response.reset(); request.setCharacterEncoding("UTF-8"); SysUser user
		 * = (SysUser) subject.getPrincipal(); logger.info(user.getUsername() +
		 * " login succ!"); // super.onLoginSuccess(token, subject, request,
		 * response); // issueSuccessRedirect(request, response);
		 * HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		 * String sessionId = httpServletRequest.getSession().getId(); user =
		 * (SysUser) subject.getPrincipal(); UserInfo userInfo = userInfoService
		 * .findByUserId(user.getId());
		 * 
		 * // return ShiroUtils.loginSuccess(userInfo, sessionId);
		 * CommonVO<UserVO> commonVO = null; commonVO = new CommonVO<UserVO>();
		 * commonVO.setCode(true); commonVO.setMessage("登陆成功"); UserVO loginVO =
		 * new UserVO(); loginVO.setAccessToken(sessionId);
		 * loginVO.setId(user.getId()); loginVO.setUsername(user.getUsername());
		 * loginVO.setUserId(user.getId());
		 * loginVO.setNickname(user.getUsername());
		 * loginVO.setAvatar(user.getAvatar()); commonVO.setData(loginVO);
		 * 
		 * PrintWriter out = response.getWriter();
		 * out.println(gson.toJson(commonVO)); out.flush(); out.close();
		 */

	}

	/**
	 * 主要是处理登入失败的方法
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		logger.info(token.getPrincipal() + ":" + token.getCredentials()
				+ " login Failure!" + e.getClass().getSimpleName());
		super.onLoginFailure(token, e, request, response);
		response.reset();
		CommonVO<Object> commonVO = null;
		commonVO = new CommonVO<Object>();
		commonVO.setCode(false);
		if (e instanceof IncorrectCredentialsException) {
			commonVO.setMessage("账号与密码不匹配");
		} else if (e instanceof AuthenticationException) {
			commonVO.setMessage(e.getMessage());
		} else {
			commonVO.setMessage("登录失败");
		}

		PrintWriter out;
		try {
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.println(gson.toJson(commonVO));
			out.flush();
			out.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return false;
	}

	/**
	 * 所有请求都会经过的方法。
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		return super.onAccessDenied(request, response);
	}

	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {
		/*
		 * AuthenticationToken authoken = createToken(username, password, true,
		 * host);
		 */
		String thirdType = WebUtils.getCleanParam(request, "thirdType");
		if (thirdType == null || thirdType.trim().equals("")) {
			String username = WebUtils.getCleanParam(request, "username");
			String password = WebUtils.getCleanParam(request, "password");
			String host = getHost(request);

			CaptchaToken upToken = new CaptchaToken();
			upToken.setUsername(username);
			upToken.setPassword(password.toCharArray());
			upToken.setRememberMe(false);
			upToken.setHost(host);
			return upToken;
		}
		if (thirdType != null && thirdType.trim().equals("qq")) {
			String openId = WebUtils.getCleanParam(request, "openId");
			String accessToken = WebUtils.getCleanParam(request, "accessToken");
			String remark = WebUtils.getCleanParam(request, "remark");
			String host = getHost(request);

			QQToken upToken = new QQToken();
			upToken.setOpenId(openId);
			upToken.setAccessToken(accessToken);
			upToken.setRememberMe(false);
			upToken.setHost(host);
			upToken.setRemark(remark);
			return upToken;
		}
		if (thirdType != null && thirdType.trim().equals("weixin")) {
			String openId = WebUtils.getCleanParam(request, "openid");
			String accessToken = WebUtils.getCleanParam(request, "accessToken");
			String remark = WebUtils.getCleanParam(request, "remark");
			String host = getHost(request);

			WxAppToken upToken = new WxAppToken();
			upToken.setOpenid(openId);
			upToken.setAccess_token(accessToken);
			upToken.setRememberMe(false);
			upToken.setHost(host);
			upToken.setRemark(remark);
			return upToken;
		}
		return null;
	}
}
